//
//  JBHomeViewController.m
//  OCsinaBlog
//
//  Created by jobo on 16/4/24.
//  Copyright © 2016年 jobo. All rights reserved.
//

#import "JBHomeViewController.h"
#import "UIBarButtonItem+extension.h"
#import "JBTowViewController.h"
#import "JBHomeTitleView.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJExtension.h"
#import "JBStatus.h"
#import "UIImageView+WebCache.h"
@interface JBHomeViewController ()


//微博数组
@property (nonatomic , strong) NSMutableArray *statuese ;
//刷新控件
@property (nonatomic ,strong) UIRefreshControl *refreshControl ;

@end

@implementation JBHomeViewController

//懒加载statuese 数组
- (NSMutableArray *)statuese
{
    if(_statuese == nil)
    {
        _statuese = [[NSMutableArray alloc] init];
    }
    return _statuese ;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    //设置下拉刷新控件
    [self setUpRefreshContorl];
    //设置导航栏按钮
    [self setUpNavigationBtn];
    //加载微博数据
    [self loadBlgHomeDataWithSince_ID:@"0"];
    
    
}
//设置下拉刷新控件
- (void)setUpRefreshContorl
{
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:self.refreshControl];
    [self.refreshControl addTarget:self action:@selector(refreshBlogHomeData) forControlEvents:UIControlEventValueChanged];
    }

//设置导航栏按钮
- (void)setUpNavigationBtn
{
    //设置左右导航控制器按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem barButtonItemWithNolImg:@"navigationbar_friendsearch" withHlgImg:@"navigationbar_friendsearch_highlighted" withTarget:self action:@selector(addFriend)] ;
    
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithNolImg:@"navigationbar_pop" withHlgImg:@"navigationbar_pop_highlighted" withTarget:self action:@selector(popAction)];
    
    
    //设置主页上的用户名按钮
    //自定义按钮
    JBHomeTitleView *btn = [JBHomeTitleView buttonWithType:UIButtonTypeCustom] ;
    //计算文字的长度
    NSString *title = @"博jo";
    
    UIFont *titleFont = [UIFont systemFontOfSize : 14] ;
    
    CGSize maxSize = CGSizeMake(MAXFLOAT, MAXFLOAT);
    
    CGSize titleSize = [title boundingRectWithSize:maxSize options:NSStringDrawingTruncatesLastVisibleLine attributes:@{NSFontAttributeName : titleFont} context:nil].size;
    
    //设置文字
    [btn setTitle:title forState:UIControlStateNormal];
    //设置按钮大小
    btn.bounds = CGRectMake(0, 0, titleSize.width + 15, titleSize.height + 5) ;
    
    //设置titleView
    self.navigationItem.titleView = btn ;

}

//添加朋友
-(void)addFriend
{
    //控制器跳转
    JBTowViewController *tow = [[JBTowViewController alloc] init] ;
    //隐藏底部导航栏
    tow.hidesBottomBarWhenPushed = YES ;
    [self.navigationController pushViewController:tow animated:YES];
    
   
}
-(void)popAction
{

}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//刷新微博数据
- (void)refreshBlogHomeData
{
    JBStatus *status = [self.statuese firstObject] ;
    NSString *since_id = status.idstr ;
    [self loadBlgHomeDataWithSince_ID:since_id];
    
}
//加载微博数据
- (void)loadBlgHomeDataWithSince_ID : (NSString *)since_id
{
    //https://api.weibo.com/2/statuses/home_timeline.json
    //获得access_token
    NSString *access_token = [[NSUserDefaults standardUserDefaults] objectForKey:@"access_token"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //网络请求参数
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
    parameters[@"access_token"] = access_token ;
    parameters[@"since_id"] = since_id  ;
    
    //get请求数据
    [manager GET:@"https://api.weibo.com/2/statuses/home_timeline.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
       
        //将数组转化成模型数据
        NSArray *statusArr = [JBStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]];
        //将数组赋值
        //[self.statuese addObjectsFromArray:statusArr];
        
        
        [self.statuese insertObjects:statusArr atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statusArr.count)]];
        //刷新界面
        [self.tableView reloadData];
        //刷新控件消失
        [self.refreshControl endRefreshing];

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark - Table view data source
//组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}
//行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
   
    return self.statuese.count;
}
//cell 数据源 ;
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    //创建cell
    //重用id
    static NSString *ID = @"statuescell" ;
    //cell重用
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(cell == nil)
    {
        //创建cell
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
    }
    
    //设置cell数据源
    JBStatus *statues = self.statuese[indexPath.row];
    cell.textLabel.text = statues.text ;
    cell.detailTextLabel.text = statues.user.screen_name ;
    [cell.imageView sd_setImageWithURL:[NSURL URLWithString:statues.user.profile_image_url] placeholderImage:[UIImage imageNamed:@"tabbar_profile"]];
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
